<template>
  <div>
    <div>
      <el-input style="width: 200px;margin:0 15px" placeholder="查询设备名" v-model="name"></el-input>
      <el-button type="primary" @click="load(1)" plain>查询</el-button>
      <el-button type="primary" @click="reset" plain>重置</el-button>
    </div>
    <div style="margin: 10px 0">
      <el-button type="primary" plain @click="handleAdd">新增</el-button>
      <el-button type="danger" plain @click="doubleDelete">批量删除</el-button>
    </div>
    <el-table :data="tableData" stripe :header-cell-style="{backgroundColor:'aliceblue',color:'#666'}"
              @selection-change="handleSelectChange">
      <el-table-column type="selection" width="55" align="center">
      </el-table-column>
      <el-table-column label="ID" prop="id"></el-table-column>
      <el-table-column label="设备名" prop="name"></el-table-column>
      <el-table-column label="水温" prop="temp" :formatter="formatWaterTemp"></el-table-column>
      <el-table-column label="水质" prop="qua"></el-table-column>
      <el-table-column label="水量" prop="count" :formatter="formatWaterVolume"></el-table-column>
      <el-table-column label="操作" align="center" width="180px">
        <template v-slot="scope">
          <div>
            <el-button size="small" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="del(scope.row.id)">删除</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <div style="margin:10px 0">
      <el-pagination
          @current-change="handleCurrentChange"
          :current-page="pageNum"
          :page-size="pageSize"
          layout="total,prev, pager, next"
          :total="total">
      </el-pagination>
    </div>
    <el-dialog title="设备信息" :visible.sync="formVisible" width="30%">
      <el-form :model="form" label-width="80px" style="padding-right: 50px" :rules="rules" ref="formRef">
        <el-form-item label="设备名" prop="name">
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="水温" prop="temp">
          <el-input type="number" v-model.number="form.temp" @input="handleInputTemp"></el-input>
        </el-form-item>
        <el-form-item label="水质" prop="qua">
          <el-select v-model="form.qua" placeholder="请选择水质">
            <el-option
                v-for="item in waterQualityOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="水量" prop="count">
          <el-input type="number" v-model.number="form.count" @input="handleInputCount"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="formVisible = false">取消</el-button>
        <el-button type="primary" @click="save">确定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import request from "@/utils/request";
import axios from "axios";

export default {
  name: "Equipment",
  data() {
    const validateTemp = (rule, value, callback) => {
      if (value > 100) {
        callback(new Error('水温不能超过100'));
      } else {
        callback();
      }
    };
    return {
      user: JSON.parse(localStorage.getItem('base-user') || '{}'),
      tableData: [],//所有数据
      pageNum: 1,//当前页码
      pageSize: 6,//每页显示个数
      name: '',
      total: 0,
      formVisible: false,
      form: {},
      waterQualityOptions: [
        { value: '优', label: '优' },
        { value: '良', label: '良' },
        { value: '普通', label: '普通' }
      ],
      rules: {
        name: [
          {required: true, message: '请输入设备名', trigger: 'blur'}
        ],
        temp: [
          { required: true, message: '请输入设备水温', trigger: 'blur' },
          { validator: validateTemp, trigger: 'blur' }
        ],
        qua: [
          {required: true, message: '请选择水质', trigger: 'blur'}
        ],
        count: [
          {required: true, message: '请输入设备水量', trigger: 'blur'}
        ]
      },
    }
  },
  created() {
    this.load()
  },
  methods: {
    handleInputTemp(value) {
      // 使用正则表达式来过滤非数字和小数点
      const filtered = value.replace(/[^\d.]/g, '').replace(/^(\d*)\.(\d{0,1}).*$/, '$1.$2');
      // 上面的正则表达式假设允许最多两位小数
      this.$set(this.form, 'temp', Number(filtered) || 0); // 使用 $set 来确保响应性
    },
    handleInputCount(value) {
      // 使用正则表达式来过滤非数字和小数点
      const filtered = value.replace(/[^\d.]/g, '').replace(/^(\d*)\.(\d{0,1}).*$/, '$1.$2');
      // 上面的正则表达式假设允许最多两位小数
      this.$set(this.form, 'count', Number(filtered) || 0); // 使用 $set 来确保响应性
    },
    formatWaterTemp(row, column, cellValue, index) {
      return cellValue + '℃';
    },
    formatWaterVolume(row, column, cellValue, index) {
      return cellValue + 'L';
    },
    doubleDelete() {
      if (!this.ids.length) {
        this.$message.warning("请选择数据")
        return
      }
      this.$confirm("确认批量删除这些数据么", "确认删除", {type: "warning"}).then(response => {
        this.$request.delete('/equipment/delete/double', {data: this.ids}).then(res => {
          if (res.code === "200") {//操作成功
            this.$message.success("操作成功")
            this.load(1)
          } else {
            this.$message.error(res.msg)
          }
        })
      }).catch(() => {
      })
    },
    handleSelectChange(rows) {
      this.ids = rows.map(v => v.id)
    },
    del(id) {
      this.$confirm("确认删除么", "确认删除", {type: "warning"}).then(response => {
        this.$request.delete('/equipment/delete/' + id).then(res => {
          if (res.code === "200") {//操作成功
            this.$message.success("操作成功")
            this.load(1)
          } else {
            this.$message.error(res.msg)
          }
        })
      }).catch(() => {
      })
    },
    handleEdit(row) {//编辑数据
      this.form = JSON.parse(JSON.stringify(row)) //给form对象赋值，注意要深拷贝数据
      this.waterQuality = this.form.qua
      this.formVisible = true
    },
    handleAdd() {//新增数据
      this.form = {}//点击新增数据的时候首先清空表
      this.waterQuality = ''
      this.formVisible = true//打开弹窗
    },
    save() { //保存按钮触发逻辑，触发新增或更新
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          this.$request({
            url: this.form.id ? '/equipment/update' : '/equipment/add',
            method: this.form.id ? 'PUT' : 'POST',
            data: this.form
          }).then(res => {
            if (res.code === '200') {
              this.$message.success('保存成功')
              this.load(1)
              this.formVisible = false
            } else {
              this.$message.error(res.msg)//输出错误信息
            }
          })
        }
      })
    },
    reset() {
      this.name = ''
      this.load()
    },
    handleCurrentChange(pageNum) {
      this.load(pageNum)
    },
    load(pageNum) {  //分页查询
      if (pageNum) this.pageNum = pageNum
      this.$request.get('/equipment/selectByPage', {
        params: {
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          name: this.name,
        }
      }).then(res => {
        // 检查 res.data 是否为 null 或 undefined
        if (res.data === null || res.data === undefined) {
          // 处理错误情况，例如显示错误消息或清空表格数据
          console.error('未获取到数据');
          this.tableData = [];
          this.total = 0;
        } else {
          // 正常处理数据
          this.tableData = res.data.records;
          this.total = res.data.total;
        }
      }).catch(error => {
        // 处理请求错误
        console.error('请求数据出错:', error);
        // 可以根据需要设置一些错误处理逻辑，比如显示错误消息
      });
    },
  }
}
</script>

<style scoped>

</style>